<?php
namespace Cmf\Controllers;

use Cmf\Models\User;
use Cmf\Forms\SignInForm;


/**
 * 登陆控制器
 */
class SessionController extends \Phalcon\Mvc\Controller
{
	public function beforeExecuteRoute()
	{
		$identity = $this->session->get('auth_identity');
		if(isset($identity['role_id']) && isset($identity['user_id'])) {
			return $this->response->redirect('index/index');
		}
	}

	public function loginAction()
	{
		$this->view->form = new SignInForm();
	}

	public function signinAction()
	{
		//是否为登录POST请求
		if($this->request->isPost()) {
			$form = new SignInForm();
			$email = $this->request->getPost('email');
			$password = $this->request->getPost('password');

			//验证登录信息
			if($form->isValid($this->request->getPost()) === false) {
				foreach($form->getMessages() as $message) {
					$this->flash->error($message);
				}

				return $this->dispatcher->forward(['controller' => 'session','action' => 'login']);
			}

			//是否存在该用户邮箱
			$user = User::findFirstByEmail($email);
			if(!$user) {
				$this->flash->error('不存在该登陆邮箱');

				return $this->dispatcher->forward(['controller' => 'session','action' => 'login']);
			}

			//查询用户信息
			$user = User::findFirst([
				'conditions' => 'email = :email: and password = :password:',
				'bind'       => ['email' => $email,'password' => $password],
			]);

			if($user) {
				$this->session->set('auth_identity',[
					'user_id'    => $user->id,
					'user_ip'    => get_client_ip(),
					'user_name'  => $user->name,
					'role_id'    => $user->role->id,
					'role_title' => $user->role->title,
				]);

				return $this->response->redirect('index/index');
			}

			$this->flash->error('登陆邮箱或登陆密码错误');

			return $this->dispatcher->forward(['controller' => 'session','action' => 'login']);
		}

		return $this->response->redirect('session/login');
	}

	public function signoutAction()
	{
		$this->session->destroy();
		$this->flash->error('退出登录成功');
		$this->response->redirect('session/login');
	}

	public function registerAction()
	{

	}
}
